package com.niodata.dp.expression.function.array;

import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorObject;
import java.lang.reflect.Array;
import java.util.List;
import java.util.Map;

public class ArrayContainsFunction extends AbstractFunction {

  @Override
  public String getName() {
    return "array.contains";
  }

  /**
   * test array contains some value.
   *
   * @param env env
   * @param array array
   * @param obj obj
   * @return contains or not
   */
  public AviatorObject call(Map<String, Object> env, AviatorObject array, AviatorObject obj) {
    Object v = array.getValue(env);
    boolean contains = false;
    if (List.class.isAssignableFrom(v.getClass())) {
      List list = (List) v;
      contains = list.contains(obj.getValue(env));
    } else if (v.getClass().isArray()) {
      Object value = obj.getValue(env);
      int len = Array.getLength(v);
      for (int i = 0; i < len; i++) {
        if (value.equals(Array.get(v, i))) {
          contains = true;
          break;
        }
      }
    }
    return FunctionUtils.wrapReturn(contains);
  }
}
